﻿#if !SILVERLIGHT4
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Redbrick.Silverlight.Common
{
    public class Lazy<_type>
    {
        private readonly object _padlock = new object();
        private readonly Func<_type> _createValue;
        private bool _isValueCreated;
        private _type _value;

        /// <summary>
        /// Initializes a new instance of the Lazy{T} class.
        /// </summary>
        /// <param name="createValue">The delegate that produces the value when it is needed.</param>
        public Lazy(Func<_type> createValue)
        {
            if (createValue == null) throw new ArgumentNullException("createValue");

            this._createValue = createValue;
        }
        public Lazy() { }

        /// <summary>
        /// Gets the lazily initialized value of the current Lazy{T} instance.
        /// </summary>
        public _type Value
        {
            get
            {
                if (!_isValueCreated)
                {
                    lock (_padlock)
                    {
                        if (!_isValueCreated)
                        {
                            if (this._createValue != null) _value = _createValue();
                            else
                            {
                                Type type = typeof(_type);
                                if (type.IsClass)
                                    this._value = Activator.CreateInstance<_type>();
                                else
                                    this._value = default(_type);
                            }
                            _isValueCreated = true;
                        }
                    }
                }
                return _value;
            }
        }

        public static implicit operator _type(Lazy<_type> l) { return l.Value; }

        /// <summary>
        /// Gets a value that indicates whether a value has been created for this Lazy{T} instance.
        /// </summary>
        public bool IsValueCreated
        {
            get
            {
                lock (_padlock)
                {
                    return _isValueCreated;
                }
            }
        }

        /// <summary>
        /// Creates and returns a string representation of the Lazy{T}.Value.
        /// </summary>
        /// <returns>The string representation of the Lazy{T}.Value property.</returns>
        public override string ToString()
        {
            return Value.ToString();
        }
    }
}

#endif
